//
//  ComposeViewController.swift
//  01-微博项目搭建
//
//  Created by Adolph on 15/6/2.
//  Copyright (c) 2015年 Adolph. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController, UITextViewDelegate {
    
    ///发送按钮
    @IBOutlet weak var send: UIBarButtonItem!
    ///textView
    @IBOutlet weak var textView: UITextView!
    ///导航栏用户名字
    @IBOutlet weak var nameLable: UILabel!
    ///toolBar的底部约束
    @IBOutlet weak var toolBottomConstraint: NSLayoutConstraint!
    
    ///发布微博的最大文本长度
    private let statusMaxLength = 140
    
    // 如果无法在 stroyboard 中，向某一个控件添加子控件，可以用代码解决
    lazy var placeholderLable: UILabel = {
        let l = UILabel(frame: CGRectMake(5,8,0,0))
        l.text = "分享新鲜事..."
        l.font = UIFont.systemFontOfSize(18.0)
        l.textColor = UIColor.lightGrayColor()
        l.sizeToFit()
        return l
        }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
       regNotification()
    }
    
    //关闭微博
    @IBAction func closeWeiBo(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 激活键盘
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 关闭键盘
        textView.resignFirstResponder()
    }
    
    ///注册通知
    private func regNotification() {
      NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillHideNotification, object: nil)
    
    }
    func keyboardChanged(notification: NSNotification) {
       println(notification)
       // 从字典中取出动画时长
    // 在 swift 中，数值可以直接从字典中提取
     let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
     // 键盘的默认高度
        var height: CGFloat = 0
    // 判断是否是 边框变化事件
        if notification.name == UIKeyboardWillChangeFrameNotification {
            // 从 userInfo 字典中，取出键盘高度
            // 字典中如果保存的是结构体，通常是以 NSValue 的形式保存的
            let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as!   NSValue).CGRectValue()
            height = rect.height
        }
        UIView.animateWithDuration(duration, animations: { () -> Void in
            self.toolBottomConstraint.constant = height
            self.view.layoutIfNeeded()
        })
    }
    deinit {
     NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func setupUI() {
      textView.addSubview(placeholderLable)
        nameLable.text = sharedUserAccount?.name
        textView.alwaysBounceHorizontal = true
    }
    
    func textViewDidChange(textView: UITextView) {
        //隐藏占位文字
        placeholderLable.hidden = !textView.text.isEmpty
        // 允许发送按钮点击
        send.enabled = !textView.text.isEmpty
        // 控制文字的字数 - 在此仍然需要判断一次文字，如果超长，需要截断文本
        // 在微博应用中，发布文本消息前，还会检测一次
        var text = textView.text as NSString
        if text.length > statusMaxLength {
            //截取最大长度的输入文本
         textView.text = text.substringFromIndex(statusMaxLength)
        
        }
    }
    /**
    如果返回 false ，通常无法正常工作
    replacementText 用户当前输入的文字，在方法中使用 text
    
    如果使用联想输入，中文已经不会走这个代理方法
    */
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        //判断回车
        if text == "\n" {
           println("回车")
        }
        // swift 中，判断字符串长度，使用 count 函数
        if count(textView.text) + count(text) > statusMaxLength {
          return false
        }
        return true
    }
    //拖拽 scrollview时，取消键盘
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        textView.resignFirstResponder()
    }
    //发送微博
    @IBAction func sendWeiBo(sender: UIBarButtonItem) {
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let params = ["access_token": sharedUserAccount!.access_token, "status": textView.text]
        NetWorkTool.requestJSON(.POST, URlString: urlString, parameters: params) { (JSON) -> () in
            println("测试---发布数据是否有返回值---")
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }

}
